package com.sky.com.sky.interceptor;

import com.sky.context.ThreadLocalUtil;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * jwt；令牌登录校验的拦截器
 * **/
@Component
@Slf4j
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * jwt令牌登录校验的拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * **/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截资源路径: {}",request.getRequestURL());

        //1. 从请求同中获取令牌
        String token = request.getHeader("token");

        //2. 校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecret(), token);
            Long empId = Long.valueOf(claims.get("empId").toString());
            //2.1 绑定变量到线程上
            ThreadLocalUtil.setCurrentId(empId);
            // 3。通过 放行
            return true;
        }catch (Exception ex){
            //4. 不通过，响应401状态码
            response.setStatus(401);
            return false;
        }

    }

    //此方法是从数据库查询信息后 最终返回给浏览器之前的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //remove方法会删除本地内存中的变量
        ThreadLocalUtil.removeCurrentId();
    }
}